package com.yiwei.jmx.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.livedetect.SuccessActivity;
import com.yiwei.jmx.MainActivity;
import com.yiwei.jmx.R;
import com.yiwei.jmx.activity.BankBindActivity;
import com.yiwei.jmx.activity.CarIdentityActivity;
import com.yiwei.jmx.activity.FaceIdentityActivity;
import com.yiwei.jmx.activity.FaceIdentityZhiMaActivity;
import com.yiwei.jmx.activity.HouseIdentityActivity;
import com.yiwei.jmx.activity.IdcardIdentityActivity;
import com.yiwei.jmx.activity.IdentityContactActivity;
import com.yiwei.jmx.activity.IncomeIdentityActivity;
import com.yiwei.jmx.activity.LoginTotalActivity;
import com.yiwei.jmx.activity.MyWechatActivity;
import com.yiwei.jmx.activity.V3XueXinIdentityActivity;
import com.yiwei.jmx.activity.WechatChatActivity;
import com.yiwei.jmx.activity.WorkIdentityActivity;
import com.yiwei.jmx.adapter.IdentityOneAdapter;
import com.yiwei.jmx.adapter.IdentityTypsInterface;
import com.yiwei.jmx.adapter.RiskNewsAdapter;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.CertificationDetailBean;
import com.yiwei.jmx.api.model.UserModel;
import com.yiwei.jmx.constant.Const;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.event.ChangeHomePageEvent;
import com.yiwei.jmx.event.UserEvent;
import com.yiwei.jmx.event.UserUnLoginEvent;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.PreferenceUtils;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.UI;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.SelectMenuTipsDilaog;
import com.yiwei.jmx.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import kangcheng.com.lmzx_android_sdk_v10.bean.Fuction;
import kangcheng.com.lmzx_android_sdk_v10.commom.sdk.LmzxSdkImpl;

/**
 * Created by xsooy-pc on 18-8-29.
 */

public class MainRiskFragment extends BaseFragment implements NestedScrollView.OnScrollChangeListener, IdentityTypsInterface {


    @BindView(R.id.layout_has_data)
    LinearLayout layoutHasData;
    @BindView(R.id.layout_no_data)
    LinearLayout layoutNoData;
    @BindView(R.id.list_one)
    RecyclerView listOne;
    @BindView(R.id.btn_fold)
    LinearLayout btnFold;
    @BindView(R.id.list_two)
    RecyclerView listTwo;
    @BindView(R.id.list_three)
    RecyclerView listThree;
    Unbinder unbinder;
    @BindView(R.id.layout_total)
    FrameLayout layoutTotal;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.layout_top)
    V19FrameLayout layoutTop;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.img_fold)
    ImageView imgFold;
    @BindView(R.id.txt_fold)
    TextView txtFold;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.txt_tips_top)
    TextView txtTipsTop;
    @BindView(R.id.txt_right_sec)
    TextView txtRightSec;
    @BindView(R.id.btn_no_score)
    TextView btnNoScore;
    @BindView(R.id.txt_point)
    TextView txtPoint;
    @BindView(R.id.txt_info)
    TextView txtInfo;
    @BindView(R.id.img_level)
    ImageView imgLevel;
    private IdentityOneAdapter identityOneAdapter;
    private IdentityOneAdapter identityTwoAdapter;
    private RiskNewsAdapter adapter;
    private float headerHeight;
    private float minHeaderHeight;
    private int[][] levelRes = {{0xffFF2740, R.mipmap.img_level_bad},
            {0xffFF4500, R.mipmap.img_level_two},
            {0xff00D39A, R.mipmap.img_level_middle},
            {0xff10BC69, R.mipmap.img_level_four},
            {0xffFF8400, R.mipmap.img_level_good},
            {0xff0072FF, R.mipmap.img_level_great},
    };
    private SelectMenuTipsDilaog identitySuccessDialog;
    private SelectMenuTipsDilaog identityIngDialog;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_main_risk;
    }

    @Override
    protected void initView() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            headerHeight = getResources().getDimensionPixelSize(R.dimen.y426);
//        } else {
//            headerHeight = getResources().getDimensionPixelSize(R.dimen.y168);
//        }
        headerHeight = getResources().getDimensionPixelSize(R.dimen.y426);
        minHeaderHeight = getResources().getDimension(R.dimen.y98);
        scrollView.setOnScrollChangeListener(this);


        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getAllIdentity();
                ((MainActivity) getActivity()).getUser();
            }
        });

        identityOneAdapter = new IdentityOneAdapter(getContext());
        identityOneAdapter.setOnChooseListener(this);
        listOne.setLayoutManager(new GridLayoutManager(getContext(), 3));
        listOne.setAdapter(identityOneAdapter);
        listOne.setNestedScrollingEnabled(false);

        identityTwoAdapter = new IdentityOneAdapter(getContext());
        identityTwoAdapter.setOnChooseListener(this);
        listTwo.setLayoutManager(new GridLayoutManager(getContext(), 3));
        listTwo.setAdapter(identityTwoAdapter);
        listTwo.setNestedScrollingEnabled(false);

        adapter = new RiskNewsAdapter(getContext());
        listThree.setAdapter(adapter);
        listThree.setNestedScrollingEnabled(false);


        EventBus.getDefault().register(this);

        if (UserInfoGlobal.isLogin()) {
            if (UserInfoGlobal.user_info != null) {
                setUserData(UserInfoGlobal.user_info);
            } else {
                ((MainActivity) getActivity()).getUser();
            }
        }
        getArticleNews();
    }

    private void initDialog() {
        if (identitySuccessDialog == null) {
            identitySuccessDialog = new SelectMenuTipsDilaog(getContext());
            identitySuccessDialog = new SelectMenuTipsDilaog(getContext()).setOnChooseListener(new SelectMenuTipsDilaog.OnChooseListener() {
                @Override
                public void onLeft() {

                }

                @Override
                public void onRight() {
                    Util.startActivity(getContext(), WechatChatActivity.class);
                }
            }).showTwoSelectData("恭喜您", R.mipmap.dialog_tips_success, "已认证成功，需要修改资料，请联系客服", "取消", "联系客服");
        }
        identitySuccessDialog.show();
    }

    private void initIngDialog() {
        if (identityIngDialog == null) {
            identityIngDialog = new SelectMenuTipsDilaog(getContext());
            identityIngDialog = new SelectMenuTipsDilaog(getContext()).setOnChooseListener(new SelectMenuTipsDilaog.OnChooseListener() {
                @Override
                public void onLeft() {

                }

                @Override
                public void onRight() {

                }
            });
            identityIngDialog.showOneSelectData("资料审核中", R.mipmap.dialog_tips_ing, "审核人员正在拼命的审核中，请耐心等待", "朕知道了").show();
        }
        identityIngDialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!UserInfoGlobal.isLogin()) {
////                        txtTipsTop.setText("当前智信分：780");
//            txtInfo.setText(UserInfoGlobal.getUserNick() + ",您好！您当前的智信分为");
//            btnNoScore.setText("快来测测你的智信分吧");
//            txtRightSec.setText("去认证");
//            layoutHasData.setVisibility(View.VISIBLE);
//            layoutNoData.setVisibility(View.GONE);
//        } else {
            txtTipsTop.setText("一秒造就你的信用报告");
            btnNoScore.setText("登录看我的信用评估");
            txtRightSec.setText("去登录");
            layoutHasData.setVisibility(View.GONE);
            layoutNoData.setVisibility(View.VISIBLE);
        }
        getAllIdentity();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UserEvent item) {
        setUserData(item.item);
    }

    private void setUserData(UserModel item) {
        txtPoint.setText(item.level.point);

        if (UserInfoGlobal.isLogin()) {
//                        txtTipsTop.setText("当前智信分：780");
            txtInfo.setText(UserInfoGlobal.getUserNick() + ",您好！您当前的智信分为");

            if (Float.valueOf(item.level.point) == 0) {
                layoutHasData.setVisibility(View.GONE);
                layoutNoData.setVisibility(View.VISIBLE);
                btnNoScore.setText("快来测测你的智信分吧");
            } else {
                layoutHasData.setVisibility(View.VISIBLE);
                layoutNoData.setVisibility(View.GONE);
            }

        }

        if (item.level.point.equals("0")) {
            txtTipsTop.setText("快来测测你的智信分吧");
            txtRightSec.setText("去认证");
        } else {

            txtTipsTop.setText("当前智信分：" + item.level.point);
            txtRightSec.setText("信用报告");
        }

        switch (item.level.level) {
            case 0:
                txtPoint.setTextColor(levelRes[0][0]);
                imgLevel.setImageResource(levelRes[0][1]);
                break;
            case 1:
                txtPoint.setTextColor(levelRes[1][0]);
                imgLevel.setImageResource(levelRes[1][1]);
                break;
            case 2:
                txtPoint.setTextColor(levelRes[2][0]);
                imgLevel.setImageResource(levelRes[2][1]);
                break;
            case 3:
                txtPoint.setTextColor(levelRes[3][0]);
                imgLevel.setImageResource(levelRes[3][1]);
                break;
            case 4:
                txtPoint.setTextColor(levelRes[4][0]);
                imgLevel.setImageResource(levelRes[4][1]);
                break;
            case 5:
                txtPoint.setTextColor(levelRes[5][0]);
                imgLevel.setImageResource(levelRes[5][1]);
                break;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UserUnLoginEvent item) {
        txtTipsTop.setText("一秒造就你的信用报告");
        btnNoScore.setText("登录看我的信用评估");
        layoutHasData.setVisibility(View.GONE);
        layoutNoData.setVisibility(View.VISIBLE);

    }


    public void getArticleNews() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }
        Api.api_service.getArticleNews().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    adapter.update(result.data);
                });
    }

    public void getAllIdentity() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }
        refresh.setRefreshing(true);

        Api.api_service.getMyCertification().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    identityOneAdapter.update(result.data.basic);
                    identityTwoAdapter.update(result.data.optional);


                });
    }

    @Override
    public void onPause() {
        super.onPause();
        if (refresh != null) {
            refresh.setRefreshing(false);
        }
    }

    private void getLmSdkKey() {
        ((MainActivity) getActivity()).getKey(UserInfoGlobal.getDealId(), false);
    }

    private void getLmSdkKeyOperator() {
        ((MainActivity) getActivity()).getKey(UserInfoGlobal.getDealId(), true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public void onScrollChange(NestedScrollView v, int x, int y, int oldScrollX, int oldScrollY) {
        //Y轴偏移量
        float scrollY = scrollView.getScrollY();
//        e3483d
        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);

        //Toolbar背景色透明度


        if (scrollY >= headerHeight) {
            layoutTop.setVisibility(View.VISIBLE);
            layoutTop.setAlpha(1);

        } else {

            if (scrollY == 0) {
                layoutTop.setVisibility(View.GONE);
            } else {
                layoutTop.setVisibility(View.VISIBLE);
                layoutTop.setAlpha(offset);
            }
        }
    }

    @Override
    public void onClick(String iscert, String remark) {
        if (UI.isFastClick()) {
            return;
        }
        if (!UserInfoGlobal.isLogin()) {
            Util.startActivity(getContext(), LoginTotalActivity.class);
            return;
        }
        if (!UserInfoGlobal.getIsIdcardPass()) {
            Dialog.showDefaultDialog(getContext(), "", "要先进行身份认证和人脸识别才能继续其他的认证", "取消", "立即认证", false, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    Util.startActivity(getContext(), IdcardIdentityActivity.class);
                }

                @Override
                public void cancel() {

                }
            });

            return;
        }
        ((MainActivity) getActivity()).bizType = remark;
        if (iscert.equals("1")) {
//            验证成功界面
            initDialog();
            return;
        } else if (iscert.equals("2")) {
            initIngDialog();
            return;
        }
        // 是否认证：-1：认证失败，0 - 未认证、 1 - 已认证、2 - 认证中，3 - 需要重新认证
        switch (remark) {
            case Const.IdentityType.yunyin:
                if (!((MainActivity) getActivity()).initSuccess) {
                    getLmSdkKeyOperator();
                    return;
                }
                if (TextUtils.isEmpty(PreferenceUtils.getString(getContext(), "mobile", "")) || Const.IS_DEBUG) {
                    LmzxSdkImpl.getInstance().initOperatorPreNo(getContext(), "", true);
                } else {
                    LmzxSdkImpl.getInstance().initOperatorPreNo(getContext(), PreferenceUtils.getString(getContext(), "mobile", ""), false);
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionMobileCarrie, 0 + "", Const.LIMU_CALLBACK);
                break;
            case Const.IdentityType.car:
                Util.startActivity(getContext(), CarIdentityActivity.class);
                break;

            case Const.IdentityType.face:
//                if (!((MainActivity) getActivity()).initSuccess) {
//                    getLmSdkKeyOperator();
//                    return;
//                }
//                LmzxSdkImpl.getInstance().setHTJCParas(getContext(), "true", "0129", "3", "8", "false", "true");
//                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKHTJC, 0 + "", Const.LIMU_CALLBACK);
                Util.startActivity(getContext(), FaceIdentityActivity.class);
                break;
            case Const.IdentityType.contacts:
                Util.startActivity(getContext(), IdentityContactActivity.class);
                break;

            case Const.IdentityType.email:
//                Util.startActivity(getContext(), V3EmailIdentityActivity.class);
                break;

            case Const.IdentityType.face_detect:
                Util.startActivity(getContext(), FaceIdentityZhiMaActivity.class);
                break;

            case Const.IdentityType.house:
                Util.startActivity(getContext(), HouseIdentityActivity.class);
                break;

            case Const.IdentityType.housefund:
                if (!((MainActivity) getActivity()).initSuccess) {
                    getLmSdkKeyOperator();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionHousingFund, 0 + "", Const.LIMU_CALLBACK);
                break;

            case Const.IdentityType.income:
                Util.startActivity(getContext(), IncomeIdentityActivity.class);
                break;

            case Const.IdentityType.jd:
                if (!((MainActivity) getActivity()).initSuccess) {
                    getLmSdkKeyOperator();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionJD, 0 + "", Const.LIMU_CALLBACK);
                break;
            case Const.IdentityType.linkedin:
                if (!((MainActivity) getActivity()).initSuccess) {
                    getLmSdkKeyOperator();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionLinkedIn, 0 + "", Const.LIMU_CALLBACK);
                break;

            case Const.IdentityType.realname:
                Util.startActivity(getContext(), IdcardIdentityActivity.class);
                break;

            case Const.IdentityType.socialsecurity:
                if (!((MainActivity) getActivity()).initSuccess) {
                    getLmSdkKeyOperator();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionSocialSecurity, 0 + "", Const.LIMU_CALLBACK);
                break;

            case Const.IdentityType.taobao:
                if (!((MainActivity) getActivity()).initSuccess) {
                    getLmSdkKeyOperator();
                    return;
                }
                LmzxSdkImpl.getInstance().start(getContext(), Fuction.LMZXSDKFunctionTaoBao, 0 + "", Const.LIMU_CALLBACK);
                break;
            case Const.IdentityType.work:
                Util.startActivity(getContext(), WorkIdentityActivity.class);
                break;
            case Const.IdentityType.xuexin:
                Util.startActivity(getContext(), V3XueXinIdentityActivity.class);
                break;
            case Const.IdentityType.bankcard:
                Util.startActivity(getContext(), BankBindActivity.class);
                break;

        }
    }

    @OnClick({R.id.btn_question, R.id.btn_no_score, R.id.btn_change_page, R.id.layout_question, R.id.txt_fold, R.id.img_fold, R.id.txt_right_sec})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.txt_fold:
            case R.id.img_fold:
                if (listTwo.getVisibility() == View.VISIBLE) {
                    listTwo.setVisibility(View.GONE);
                    txtFold.setText("展开");
                } else {
                    listTwo.setVisibility(View.VISIBLE);
                    txtFold.setText("收起");
                }
                break;
            case R.id.txt_right_sec:
                if (UI.toString(txtRightSec).equals("去登录"))
                    Util.startActivity(getContext(), LoginTotalActivity.class);
                break;
            case R.id.layout_question:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(getContext(), LoginTotalActivity.class);
                    return;
                }
                Util.startActivity(getContext(), MyWechatActivity.class);
                break;
            case R.id.btn_change_page:
                EventBus.getDefault().post(new ChangeHomePageEvent(2));
                break;
            case R.id.btn_question:
                Dialog.showRiskTipsDialog(getContext(), new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {

                    }

                    @Override
                    public void cancel() {

                    }
                });
                break;
            case R.id.btn_no_score:
                if (UI.toString(btnNoScore).equals("登录看我的信用评估")) {
                    Util.startActivity(getContext(), LoginTotalActivity.class);
                }
                break;
        }
    }
}
